package org.xiaoyu.rpc.remoting.transport;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.util.ReferenceCountUtil;

import java.util.List;

/**
 * Created By Have
 * 2021/7/14 20:40
 */
@Deprecated
public class MyDynamicLengthFrameDecoder extends ByteToMessageDecoder {

    private final int frameLength;
    /**
     * Creates a new instance.
     *
     * @param frameLength the length of the frame
     */
    public MyDynamicLengthFrameDecoder(int frameLength) {
        this.frameLength = frameLength;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() <= 0) {
            return;
        }
        ByteBuf buf = in.retainedDuplicate();
        ReferenceCountUtil.retain(in);
        resolve(ctx.channel(), buf, out);
        in.skipBytes(in.readableBytes());
    }

    protected void resolve(Channel channel, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() < frameLength) {
            out.add(in);
        } else {
            while (in.readableBytes() > 0) {
                ByteBuf buffer = channel.alloc().buffer(Math.min(1024, in.readableBytes()));
                in.readBytes(buffer);
                out.add(buffer);
            }
        }
    }

}
